import React, { Component,Fragment } from 'react';

import { axiosConfig } from '../../utils/ajax/config';
import { Catch } from '../../utils';
import {
    Upload,
    Icon,
    Modal
} from 'antd';
import "./index.less";
import { Tip } from '../index';
import { Conf } from '../../utils';

export default class Index extends Component{
    state = {
        previewVisible: false,
        previewImage: '',
        removeBool:false,
        headers:{
            Authorization:Catch.get('access_token')
        },
        fileList:[],
        data:{
            type:'photo',
            path:'default',
            size:4
        },
        listType:"picture-card",
        loading:false,
        accept:'image/*',
        filevalue:[]
    }
    render(){
        const { previewVisible, previewImage, fileList, headers, data, accept, listType } = this.state;
        const { length } = this.props;

        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传</div>
            </div>
        );
        return(
            <Fragment>
                <Upload
                    action={axiosConfig.baseURL+'upload'}
                    headers = {headers}
                    data = {data}
                    fileList = {fileList}
                    accept = {accept}
                    listType = {listType}
                    onPreview = {this.handlePreview}
                    onRemove = {this.handleRemove}
                    beforeUpload = {this.beforeUpload}
                    onChange = {this.handleChange}
                    //{...this.state}
                >
                    {fileList.length >= length ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt={fileList.name} style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Fragment>
        )
    }

    static getDerivedStateFromProps(nextProps, prevState){
        // if(
        //     prevState.fileList === undefined
        //     || prevState.removeBool === true
        //     || prevState.fileList !== nextProps.fileList
        //     || prevState.loading !== nextProps.loading
        // ){
        //     let nextState = Object.assign(prevState, nextProps);
        //     return{
        //         ...nextState,
        //         removeBool:false
        //     }
        // }
        return{
            ...prevState,
            removeBool:false
        }
        //return null;
    }

    shouldComponentUpdate(prevProps, prevState){
        if(!prevState.removeBool){
            return true;
        }else{
            return false;
        }
    }
    
    componentDidMount(){
        let { fileList, setValue, fieldname, fieldvalue } = this.props;
        const { data } = this.state;
        let newdata = Object.assign(data, this.props.data);

        this.setState({
            fileList,
            setValue,
            fieldname,
            fieldvalue,
            data:newdata
        })
    }

    //取消图片查看
    handleCancel = () => this.setState({ previewVisible: false })
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    handleRemove = ( file )=>{
        const { fileList, setValue, fieldname }= this.state
        for (let i = 0; i < fileList.length; i++) {
            if(fileList[i].uid === file.uid){
                fileList.splice(i, 1);
                break;
            }
        }

        let newvalue = [];
        for (let i = 0; i < fileList.length; i++) {
            newvalue.push((fileList[i]['url']).substr(Conf.fileUrl.length))
        }
        
        let newvalueStr = newvalue.join(';');
        setValue(fieldname,newvalueStr);

        this.setState({
            fileList
            ,removeBool:true
            ,fieldvalue:newvalueStr
        })
    }

    beforeUpload = (file)=>{
        const { size,type } = this.state.data;
        const isJPG = type==='photo' || file.type.indexOf("image/") !== -1 ;
        if (!isJPG) {
            Tip.Message('只能上传图片类型!','error');
        }
        const isLt4M = file.size / 1024 / 1024 < size;
        if (!isLt4M) {
            Tip.Message('上传大小不能超过'+size+'MB!','error');
        }
        return isJPG && isLt4M;
    }
    
    handleChange = ({ fileList,file,event }) => {
        const { setValue, fieldname }= this.state
        let newvalue = []; //Luck.noempty(fieldvalue.split(";"))
        if (file.status === 'done') {
            if(file.response.code === 0){
                fileList = fileList.map((file1) => {
                    if (file1.response) {
                        file1.url = Conf.fileUrl + file1.response.url;
                        newvalue.push(file1.response.url)
                    }
                    return file1;
                });
            }else{
                fileList = fileList.map((file1) => {
                    if (file1.uid === file.uid) {
                        file1.status = 'error';
                    }
                    return file1;
                });
                Tip.Message(file.response.msg,'error');
            }
        }
        let newvalueStr = newvalue.join(';');
        setValue(fieldname,newvalueStr);
        this.setState({
            fileList:[...fileList]
            ,removeBool:true,
            fieldvalue:newvalueStr
        })
    }
}